package com.anjufang.oauth2;

import com.anjufang.entity.AdminUser;
import com.anjufang.entity.AdminUserToken;
import com.anjufang.service.system.ShiroService;
import com.anjufang.utils.TokenManager;
import com.anjufang.utils.constant.Constant;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;


/**
 * 认证
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
	@Autowired
	private ShiroService shiroService;

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof OAuth2Token;
	}

	/**
	 * 授权(验证权限时调用)
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		AdminUser user = (AdminUser) principals.getPrimaryPrincipal();
		Long userId = user.getId();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Session session = TokenManager.getSession();
		Set<String> permisstions = (Set<String>) session.getAttribute(Constant.PERMISSTIONS);
		if (permisstions == null) {
			// 根据用户ID查询权限（permission），放入到Authorization里。
			permisstions = shiroService.getUserPermissions(userId);
			// permisstions = new HashSet<String>(Collections3.extractToList(permisstions,
			// "url"));
			session.setAttribute(Constant.PERMISSTIONS, permisstions);
		}
		info.setStringPermissions(permisstions);
		// 用户权限列表
		// Set<String> permsSet = shiroService.getUserPermissions(userId);

		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String accessToken = (String) token.getPrincipal();

		// 根据accessToken，查询用户信息
		AdminUserToken tokenEntity = shiroService.queryByToken(accessToken);
		// token失效
		if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
			throw new IncorrectCredentialsException("token失效，请重新登录");
		}

		// 查询用户信息
		AdminUser user = shiroService.queryUser(tokenEntity.getUserId());
		// 账号锁定
		if (user.getStatus() == 0) {
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
		return info;
	}
}
